package sg.edu.nus.iss.club;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;
import java.io.Serializable;

public class BookingRegister implements Serializable {

	private HashMap <Facility,ArrayList<Booking>> bookingTable;
	
	public BookingRegister(){
		bookingTable = new HashMap <Facility,ArrayList<Booking>>();
	}
	
	public void addBooking(Member m, Facility f, Date startDate, Date endDate) throws BadBookingException{
		Booking booking = new Booking (m, f, startDate, endDate);
		ArrayList <Booking> bookingArr = bookingTable.get(f);
		if (bookingArr == null) {
			bookingArr = new ArrayList <Booking>();
			bookingArr.add(booking);
			bookingTable.put(f, bookingArr);
		}else {
			for (int n =0; n< bookingArr.size(); n ++) {
				if (booking.overlaps(bookingArr.get(n))){
					throw new BadBookingException ("overlaps previous booking");
				}
			}
			//no overlap
			bookingArr.add(booking);
		}
	}
	
	
	public ArrayList<Booking> getBooking(Facility f, Date startDate, Date endDate){
		
		ArrayList <Booking> bookingArrSameF = bookingTable.get(f);
		ArrayList <Booking> result = new ArrayList <Booking>();
		
		if (bookingArrSameF == null || bookingArrSameF.size() ==0) {
			
			return null;
		}else {
	
			for (int n =0; n< bookingArrSameF.size(); n ++) {
				if ( (!bookingArrSameF.get(n).getStartDate().before(startDate))&& 
					(!bookingArrSameF.get(n).getEndDate().after(endDate))){ //include equals
					result.add(bookingArrSameF.get(n));
				}
					
			}//end of for
			return result;
		
		}
	}
	
	
	public void removeBooking (Booking b) {
		ArrayList <Booking> bookingArrSameF = bookingTable.get(b.getFacility());
		
		if (bookingArrSameF == null || bookingArrSameF.size() ==0) {
			
			return;
		}else {
	
			for (int n =0; n< bookingArrSameF.size(); n ++) {
				if (bookingArrSameF.get(n).equals(b)){ //TODO test booking equals method
					bookingArrSameF.remove(n);
				}
					
			}//end of for
			
			//TODO test if need to set back this arrList to hashmap?
		
		}
	}
}
